package com.aosan.website.auth.service

import com.aosan.website.admin.dto.Principal
import com.aosan.website.admin.feign.UserClient
import com.aosan.website.common.core.constant.UserStateConstant
import org.springframework.security.core.authority.AuthorityUtils
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service
import org.springframework.security.core.userdetails.UserDetailsService as IUserDetailsService

@Service
class UserDetailsService(
        val userClient: UserClient
) : IUserDetailsService {

    @Throws(UsernameNotFoundException::class)
    override fun loadUserByUsername(username: String): UserDetails {
        val user = userClient.getUserByUsername(username) ?: throw UsernameNotFoundException("用户不存在！")
        return user.run {
            Principal(
                    name,
                    password,
                    UserStateConstant.ENABLE == status,
                    UserStateConstant.EXPIRED != status,
                    UserStateConstant.CREDENTIAL_EXPIRED != status,
                    UserStateConstant.LOCK != status,
                    AuthorityUtils.commaSeparatedStringToAuthorityList(roleId))
        }

    }
}